package com.superyee.commonlib.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.Gravity;

import androidx.appcompat.widget.AppCompatTextView;

import com.superyee.commonlib.R;

public class RoundTextView extends AppCompatTextView {

    private Paint circlePaint;
    private Paint bgPaint;
    private int storkColor = Color.TRANSPARENT;
    private int circleBgColor = Color.TRANSPARENT;
    private float storkWidth;

    public RoundTextView(Context context) {
        this(context, null);
        configPaint(null);
    }

    public RoundTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        configPaint(attrs);
    }

    public RoundTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        configPaint(attrs);
    }

    private void configPaint(AttributeSet attrs) {
        setGravity(Gravity.CENTER);
        circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        circlePaint.setStyle(Paint.Style.STROKE);
        bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        bgPaint.setStyle(Paint.Style.FILL);
        storkWidth = 0;
        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.RoundTextView);
            storkColor = typedArray.getColor(R.styleable.RoundTextView_storkColor, storkColor);
            circleBgColor = typedArray.getColor(R.styleable.RoundTextView_bgColor, circleBgColor);
            storkWidth = typedArray.getDimension(R.styleable.RoundTextView_storkWidth, storkWidth);
            typedArray.recycle();
        }
        if (storkWidth != 0) {
            circlePaint.setStrokeWidth(storkWidth);
            circlePaint.setColor(storkColor);
        }
        bgPaint.setColor(circleBgColor);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int height = getHeight();
        int width = getWidth();
        int radius = Math.min(width / 2, height / 2);
        int storkRadius;
        storkRadius = (int) (radius - storkWidth);
        radius = storkRadius - 1;
        if (storkWidth != 0)
            canvas.drawCircle(width / 2, height / 2, storkRadius, circlePaint);
        canvas.drawCircle(width / 2, height / 2, radius, bgPaint);
        super.onDraw(canvas);
    }

}
